<?php
/**
 * Created by PhpStorm.
 * User: luoshuqi
 * Date: 19-2-15
 * Time: 上午11:37
 */

namespace App\Models;


use App\Utils\PasswordTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class SysUser extends Model
{
    use SoftDeletes, PasswordTrait;

    public static function findByUsername(string $username): ?SysUser
    {
        return self::query()->where('username', $username)->first();
    }

    public static function deleteById(...$id): void
    {
        self::query()->whereIn('id', $id)->update([
            'deleted_at' => DB::raw('NOW()'),
            'username' => DB::raw('CONCAT(username, "@", UNIX_TIMESTAMP())')
        ]);
    }

    public static function deleteByGroupId(...$groupId): void
    {
        self::query()->whereIn('group_id', $groupId)->update([
            'deleted_at' => DB::raw('NOW()'),
            'username' => DB::raw('CONCAT(username, "@", UNIX_TIMESTAMP())')
        ]);
    }

    public function verifyPassword(string $password): bool
    {
        return $this['password'] === $this->password($password);
    }

    public function group()
    {
        return $this->belongsTo(SysGroup::class);
    }

    public function getEnabledAttribute()
    {
        return $this->attributes['enabled'] === 1;
    }

    public function setEnabledAttribute(bool $value)
    {
        $this->attributes['enabled'] = $value ? 1 : 0;
    }

    public function setPasswordAttribute(string $value)
    {
        $this->attributes['password'] = $this->password($value);
    }
}